const db = require('../../database/index')

// 获取文章分类
const handlerArticleCate = (req, res) => {
  const sql = 'select id,name,alias from ev_article_cate where is_delete=0'
  db.query(sql, (err, results) => {
    if (err) {
      console.log(err)
    } else if (results.length > 0) {
      return res.send({
        status: 1,
        code: 200,
        msg: '获取成功',
        data: {
          results
        }
      })
    } else {
      return res.cc('程序异常')
    }

  })
}

// 新增文章分类
const handlerAddArticleCate = (req, res) => {
  // 查询分类名称或者别名是否被占用
  const sqlCate = 'select * from ev_article_cate where name=? or alias=?'
  db.query(sqlCate, [req.body.name, req.body.alias], (err, results) => {
    if (err)
      return res.cc(err)
    if (results.length > 0) {
      let msg = results[0].name === req.body.name ? '分类名称' : '别名'
      return res.cc(msg + '被占用')
    } else {
      addCate()
    }
  })

  const addCate = () => {
    let way = '', data = [], msg = ''
    way = req?.params?.id ? 'update ev_article_cate set ? where id=?' : 'insert into ev_article_cate set ?'
    data = req?.params?.id ? [req.body, req.params.id] : req.body
    msg = req?.params?.id ? '更新成功' : '新增成功'
    db.query(way, data, (err, results) => {
      if (err) {
        return res.cc(err)
      } else if (results.affectedRows > 0) {
        return res.cc(msg,1)
      } else {
        return res.cc('未知错误')
      }
    })
  }
}

// 删除文章分类
const handlerDelArticleCate = (req, res) => {
  const sql = 'update ev_article_cate set is_delete=1 where id=?'
  db.query(sql, [req.params.id], (err, results) => {
    if (err) {
      return res.cc(err)
    } else if (results.affectedRows > 0) {
      return res.cc('删除成功',1)
    } else {
      return res.cc('未知错误')
    }
  })
}

// 根据id获取文章分类
const handlerGetArticleCateById = (req, res) => {
  const sql = 'select * from ev_article_cate where id=?'
  db.query(sql, [req.params.id], (err, results) => {
    if (err) {
      return res.cc(err)
    } else if (results.length > 0) {
      return res.send({
        status: 1,
        code: 200,
        msg: '获取成功',
        data: {
          results
        }
      })
    } else {
      return res.cc('程序异常')
    }
  })
}

module.exports = {
  handlerArticleCate,
  handlerAddArticleCate,
  handlerDelArticleCate,
  handlerGetArticleCateById,

}
